package com.linxin.ai_automates_periodontal_treatment_system.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.linxin.ai_automates_periodontal_treatment_system.entity.Doctor;


import java.util.Date;

public class JwtUtil {

    private static final String SECRET_KEY = "linxin";  // 请替换为真实的秘钥

    // 生成token
    public static String generateToken(Doctor doctor) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            return JWT.create()
                    .withClaim("username", doctor.getAccount())
                    // 设置过期时间为7天
                    .withExpiresAt(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000))
                    .sign(algorithm);
        } catch (JWTCreationException exception){
            // 生成token失败
            return null;
        }
    }

    // 验证token
    public static boolean verifyToken(String token, Doctor user) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("username", user.getAccount())
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            // token验证通过
            return true;
        } catch (Exception exception){
            // token验证失败
            return false;
        }
    }

    /**
     * 获取token中的username
     * @param token
     * @return
     */
    public static String getAccountFromToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("username").asString();
        } catch (Exception exception){
            // token验证失败
            return null;
        }
    }

}
